package org.example.netty.httpserver.json;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.httpserver.codec.ByteToJSON;
import org.example.netty.httpserver.codec.JSONToByte;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class JSONClient {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();

        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group);

        bootstrap.channel(NioSocketChannel.class);
        // 立即发送
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                // 消息转换成字节
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                ch.pipeline().addLast(new JSONToByte());
                // 字节转换成消息
                ch.pipeline().addLast(new ByteToJSON());
                ch.pipeline().addLast(new JSONEchoClientHandler());
            }
        });

        log.info("开始连接服务端");
        final ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    log.info("连接成功");
                } else {
                    log.info("服务连接失败");
                }
            }
        });

        try {
            final Channel channel = future.sync().channel();
            log.info("服务连接成功");
            // 连接成功处理
            Scanner scanner = new Scanner(System.in);
            while (true) {
                log.info("输入消息内容");
                String content = scanner.next();
                channel.writeAndFlush(JSONData.builder().content(content).build().toJson());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
